package com.zj.auth.service.common;

import com.zj.auth.bean.AuthCode;
import com.zj.auth.cache.RedisUtil;
import com.zj.auth.domain.Customer;
import com.zj.auth.repository.CustomerRepository;
import cn.zj.smart.util.StringUtil;
import cn.zj.smart.util.exception.AuthException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author xi.yang
 * @create 2020-11-19 20:55
 **/
@Service("PHONELoginImpl")
public class PhoneLoginImpl extends CommonAuthImpl {
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public void validate() {
        super.validate();
        if (StringUtil.isBlank(this.loginTo.getPassword())) {
            throw new AuthException(AuthCode.PASSWORD_MUST_NOT_NULL);
        }
        // 先用123456来测试
        if (!"123456".equals(this.loginTo.getPassword())) {
            throw new AuthException(AuthCode.PHONE_CODE_ERROR);
        }
//        // 验证验证码
//        boolean result = redisUtil.validatePhoneCode(this.loginTo.getAccount(), this.loginTo.getPassword());
//        if (!result) {
//            throw new AuthException(AuthCode.PHONE_CODE_ERROR);
//        }
    }

    @Override
    public Customer getCustomer() {
        return customerRepository.findByPhone(this.loginTo.getAccount());
    }

    @Override
    public Customer registerCustomer() {
        Customer customer = new Customer();
        customer.setCreateTime(new Date());
        customer.setPhone(this.loginTo.getAccount());
        customer.setUsername(StringUtil.hiddenPhone(this.loginTo.getAccount()));
        return customerRepository.save(customer);
    }
}
